<script setup lang="ts">
import type { DataAction } from '../DataForm/types'
import { useElementSize } from '@vueuse/core'
import { computed, useTemplateRef } from 'vue'
import { doDataAction } from '../DataForm/types'

const { actions, row, rowIndex } = defineProps<{
  row: any
  rowIndex: number
  actions: DataAction[]
}>()

const showButtons = computed(() => {
  return actions.filter(a => a.show === undefined || a.show(row))
})

const el = useTemplateRef('el')
const { width } = useElementSize(el)
const showButtonCount = computed(() => {
  let w = 0
  let count = 0

  for (const b of showButtons.value) {
    const title = (typeof b.label === 'function') ? b.label(row) : b.label
    w += title.length * 10 + 10
    if (w > (width.value - 40)) {
      break
    }
    count++
  }
  return count
})

async function handleClick(index: number) {
  const b = showButtons.value[index]
  await doDataAction(row, b, rowIndex)
}
</script>

<template>
  <div v-if="showButtons.length > 0" ref="el" class="flex flex-row">
    <template v-for="(b, index) in showButtons" :key="index">
      <div v-if="index < showButtonCount" class="button-center">
        <el-button link :type="typeof b.type === 'function' ? b.type(row) : b.type " @click.stop="handleClick(index)">
          <div>
            {{ (typeof b.label === 'function') ? b.label(row) : b.label }}
          </div>
        </el-button>
      </div>
    </template>

    <el-dropdown
      v-if="showButtons.length > showButtonCount" placement="bottom-end" class="button-center"
      @command="(index) => handleClick(index)"
    >
      <el-button link type="primary" @click.stop="">
        <div>
          更多
        </div>
        <div class="i-tdesign-chevron-down" />
      </el-button>
      <template #dropdown>
        <el-dropdown-menu>
          <template v-for="(b, index) in showButtons" :key="index">
            <el-dropdown-item v-if="index >= showButtonCount" :command="index">
              <el-text :type="typeof b.type === 'function' ? b.type(row) : b.type ">
                {{ (typeof b.label === 'function') ? b.label(row) : b.label }}
              </el-text>
            </el-dropdown-item>
          </template>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<style scoped>
.button-center {
  --at-apply: flex items-center justify-center;
}

.el-button:focus-visible {
  outline: none;
}
</style>
